import {
  registerDecorator,
  ValidationArguments,
  ValidationOptions,
} from "class-validator";
import { Types as MongooseTypes } from "mongoose";

/**
 *
 * @author  quantumsheep ====>>>> https://github.com/quantumsheep/class-validator-mongo-object-id
 *
 *
 */

export function IsObjectId(
  validationOptions?: ValidationOptions
): PropertyDecorator {
  return (object: object, propertyName: string) => {
    registerDecorator({
      name: "isObjectId",

      target: object.constructor,
      propertyName,
      options: validationOptions,
      validator: {
        defaultMessage: ({ property, value }) => {
          return `${property}应该是一个 ObjectId而不是${value}`;
        },
        validate(value: any, args: ValidationArguments) {
          return MongooseTypes.ObjectId.isValid(value);
        },
      },
    });
  };
}
